from datetime import datetime
from django.db import transaction
from django.http import JsonResponse
from django.views import View
import json
from aijia_zufang.utils.iflogin import IfloginMixin
from homes.models import House
from orders.models import Order

class Addorder(IfloginMixin,View):
    def post(self,request):
        dict = json.loads(request.dict)
        house_id = int(dict.get('house_id'))
        begin_date	= dict.get('start_date')
        end_date = dict.get('end_date')
        #校验
        if not all([house_id,begin_date,end_date]):
            return  JsonResponse({
                'errno':400,
                'errmsg':'缺少参数' })
        try:
            begin_date = datetime.strptime( begin_date, '%Y-%m-%d' )  # 转换起始日期格式
            end_date = datetime.strptime( end_date, '%Y-%m-%d' )  # 转换结束日期格式
        except Exception as e:
            return JsonResponse( {
                'errno': 400,
                'errmsg': '缺少参数'} )

        days = (end_date - begin_date).days

        if days < 0:
            return JsonResponse( {
                'errno': 400,
                'errmsg': '起始日期超过结束日期'} )

        count = Order.objects.filter( house=house_id, start_date__gt=begin_date,
                                      end_date__lt=end_date, status__in=[0, 1, 2] ).count()
        if count:
            return JsonResponse( {
                'errno': 400,
                'errmsg': '房子已经被预定'} )
        while True:
            try:
                house = House.objects.get( id=house_id )  # 当前选择的房屋
            except Exception as e:
                return JsonResponse( {
                    'errno': 400,
                    'errmsg': '获取房屋信息异常'} )
            if not house:
                return JsonResponse( {
                    'errno': 400,
                    'errmsg': '房屋id错误'} )


            if days < house.min_days:
                return JsonResponse( {
                    'errno': 400,
                    'errmsg': '入住天数小于最少入住天数'} )
            elif (days > house.max_days) and house.max_days !=0 :
                return JsonResponse( {
                'errno': 400,
                'errmsg': '入住天数大于最多入住天数'} )

            old_count = house.order_count
            new_count = house.order_count + 1

            count = House.objects.filter( id = house_id,
                                              order_count = old_count ).update(
                                              order_count = new_count )
            if count == 0:
                continue
            amount = days * house.price
            order = Order.objects.create(
                user=request.user,
                house=house_id,
                begin_date=begin_date,
                end_date=end_date,
                days=days,
                house_price=house.price,
                amount=amount,
                status=1 )
            break
        return JsonResponse({
            "errno": 0,
            "errmsg": "下单成功",
            "data":{"order_id": order.id}})


class OrderRejectOrderView(IfloginMixin,View):
    '''接单和拒单'''
    def put(self, request, order_id):
        '''接受参数'''
        data = json.loads(request.body.decode())
        action = data.get('action')

        # 校验参数
        if action not in('accept', 'reject'):
            return JsonResponse({
                'errno':4004,
                'errmsg': '获取数据错误'})

        # 获取订单房屋
        try:
            order = Order.object.filter(id=order_id, status=Order.ORDER_STATUS['WAIT_ACCEPT']).first()
            house = order.house
        except Exception as e:
            return JsonResponse({'errno': 4001,
                                 'errmsg': '获取数据错误'})

        # 判断订单是否存在并且当前房屋的用户id是当前用户的id
        if not order or house.user != user:
            return JsonResponse({'errno': 4002,
                                 'errmsg': '数据有误'})
        # 接单
        if action == 'accept':
            order.status = Order.ORDER_STATUS['WAIT_COMMENT']

        elif action == 'reject':
            # 获取拒单原因
            reason = data.get('reason')
            if not reason:
                return JsonResponse({'errno':400,
                                     'errmsg': '用户未填写原因'})

            # 设置状态为拒单并且设置拒单原因
            order.status = Order.ORDER_STATUS['REJECTED']
            order.comment = reason

        # 保存到数据库
        try:
            order.save()
        except Exception as e:
            return JsonResponse({'errno':4001,
                                 'errmsg': '保存订单状态失败'})

        return JsonResponse({'errno':0,
                             'errmsg':'操作成功'})



        #     "data":{"order_id": order}
        # })





        #     #获取当前房屋重合的日期区间的数量来查看是否有预定

        #
        # if count > 0:
        #
        #
        #
        #
        #
        #
        #

